//
//  Target.swift
//  ASW
//
//  Created by zhuxuhong on 2020/12/2.
//

import BWExtensionKit
import Moya

public struct Target: TargetType {
    public var request: Request
    
    public init(request: Request) {
        self.request = request
    }
    public var baseURL: URL {
        return request.host.url
    }
    public var path: String {
        return request.path
    }
    public var method: Moya.Method {
        return .init(rawValue: request.method.rawValue)
    }
    public var sampleData: Data = "".data(using: .utf8)!
    
    public var validationType: ValidationType {
        return .successCodes
    }
    public var task: Task
    {
        switch request.taskType
        {
        case .plain:
            return .requestPlain
            
        case .formUrlEncoded:
            let data = request.params.bw_urlParamsJoined.data(using: .utf8) ?? .init()
            return .requestCompositeData(bodyData: data, urlParameters: [:])
            
        case .uploadFileURL(let fileURL):
            return .uploadFile(fileURL)
            
        case .uploadFileDatas(let datas):
            return .uploadCompositeMultipart(datas, urlParameters: request.params)
            
        case .formData, .jsonBody:
            guard let paramsData = request.params.bw_jsonData() else {
                return .requestData(.init())
            }
            return .requestData(paramsData)
            
        case .urlParameters:
            return .requestParameters(parameters: request.params, encoding: URLEncoding.default)
        
        case .jsonParams:
            return .requestParameters(parameters: request.params, encoding: JSONEncoding.default)
        
        case .downloadURL(let saveURL):
            return .downloadDestination { _, response in
                var aURL = saveURL
                if aURL.hasDirectoryPath {
                    let name = response.suggestedFilename ?? String(Date().timeIntervalSince1970)
                    aURL = aURL.appendingPathComponent(name)
                }
                return (destinationURL: aURL, options: [
                    .createIntermediateDirectories,
                    .removePreviousFile
                ])
            }
        
        case .downloadParams(let saveURL):
            return .downloadParameters(parameters: request.params, encoding: JSONEncoding.default, destination: { (tmpURL, response) in
                return (destinationURL: saveURL, options: [
                    .createIntermediateDirectories,
                    .removePreviousFile
                ])
            })
        }
    }
    public var headers: [String: String]? {
        return request.headers
    }
}
